import React, { Component, useContext, useState, useEffect, useRef } from 'react';
import { Table, Space, Button, Breadcrumb, AutoComplete, Form, Input, Modal, Pagination, Select, message, } from 'antd';
import { AppstoreTwoTone, PlusOutlined, MinusCircleOutlined, DeleteOutlined, PlusCircleOutlined, } from '@ant-design/icons'
import styles from './standardList.less'
import { connect, } from 'dva';
const { Option } = AutoComplete;
// const { Option } = Select;
const EditableContext = React.createContext(null);

const EditableRow = ({ index, ...props }) => {
    const [form] = Form.useForm();
    return (
        <Form form={form} component={false}>
            <EditableContext.Provider value={form}>
                <tr {...props} />
            </EditableContext.Provider>
        </Form>
    );
};

const EditableCell = ({
    typeList,
    title,
    editable,
    children,
    dataIndex,
    record,
    handleSave,
    ...restProps
}) => {
    const [editing, setEditing] = useState(false);
    const inputRef = useRef(null);
    const form = useContext(EditableContext);
    useEffect(() => {
        if (editing) {
            inputRef.current.focus();
        }
    }, [editing]);

    const toggleEdit = () => {
        // console.log("toggleEdit", e)
        setEditing(!editing);
        form.setFieldsValue({
            [dataIndex]: record[dataIndex],
        });
    };

    const save = async () => {
        try {
            const values = await form.validateFields();
            toggleEdit();
            handleSave({ ...record, ...values });
        } catch (errInfo) {
            console.log('Save failed:', errInfo);
        }
    };

    let childNode = children;

    const [result, setResult] = useState([]);

    if (editable) {
        childNode = editing ? (
            <div>
                <Button type="link" onClick={save} >保存</Button>

                {
                    title === "类型" ?
                        <Form.Item
                            name={dataIndex}
                            rules={
                                [
                                    {
                                        required: true,
                                        message: `${title} 必填.`,
                                    },
                                ]
                            }
                        >
                            <Select ref={inputRef} >
                                {
                                    typeList.map((item, index) => {
                                        return <Option key={item.dicId} value={item.dicCode} >{item.dicName}</Option>
                                    })
                                }
                            </Select>
                        </Form.Item>

                        :
                        title === "名称" ?
                            <Form.Item
                                name={dataIndex}
                                rules={
                                    [
                                        {
                                            required: true,
                                            message: `${title} 必填.`,
                                        },
                                    ]
                                }>

                                < Input ref={inputRef} />
                            </Form.Item>
                            :
                            <Form.Item
                                name={dataIndex}
                                rules={
                                    [
                                        {
                                            pattern: /^[1-9][0-9]*$/,
                                            required: true,
                                            message: `${title}类型错误.`,
                                        },
                                    ]
                                }
                            >

                                < Input ref={inputRef} />
                            </Form.Item>

                }
            </div>
        ) : (
            <div
                className="editable-cell-value-wrap"
                style={{
                    paddingRight: 24,
                }}
                onClick={toggleEdit}
            >
                {children}
            </div>
        );
    }

    return <td {...restProps}>{childNode}</td>;
};
@connect((global) => ({
    userInfo: global.userInfo,
}))
class StandardMetaDataForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            currentPage: 1,
            pageSize: 10,
            data: [],//表格数据
            isModalVisible: false,
            modalTitle: "",//弹框标题
            typeList: [],
            moreForm: {},
            initvalue: [],//更多的已有数据
            seValuelength: 0,//选择项编辑前的个数
            beginmoreFormData: [],//编辑前选择项数据
            deleteId: "",//选择项删除id
            addFlag: false,
            receiveStandardId: "",//传过来的标准id
            isEditing: false,//编辑行
        }
        //定义表头
        this.columns = [
            {
                title: '名称',
                dataIndex: 'name',
                align: "center",
                key: 'name',
                editable: true,
                width: 200
            },
            {
                title: '类型',
                dataIndex: 'type',
                align: "center",
                key: 'type',
                editable: true,
                width: 200,
                render: (text, record, index) => <p>{record.typeName}</p>
            },

            {
                title: '限制(字符)',
                key: 'limits',
                align: "center",
                dataIndex: 'limits',
                editable: true,
                width: 200
            },
            {
                title: '排序',
                key: 'sort',
                align: "center",
                dataIndex: 'sort',
                editable: true,
                width: 200
            },
            {
                title: '操作',
                key: 'action',
                align: "center",
                width: 300,
                render: (text, record, index) => (
                    <Space size="small">
                        {
                            record.typeName === "单选" ||
                                record.typeName === "多选" ||
                                record.typeName === "下拉选"
                                ?
                                <div>
                                    <Button type="link"
                                        icon={<DeleteOutlined />}
                                        danger
                                        size="small"
                                        onClick={() => this.handleDelete(record)}>删除</Button>
                                    <Button type="link"
                                        icon={<PlusCircleOutlined />}
                                        size="small"
                                        title="增加选项"
                                        onClick={() => this.getMore(record, 1)}>增加选项</Button>
                                    <Button type="link"
                                        icon={<MinusCircleOutlined />}
                                        size="small"
                                        title="删减选项"
                                        onClick={() => this.getMore(record, 0)}>删减选项</Button>
                                </div>
                                :
                                <Button type="link"
                                    icon={<DeleteOutlined />}
                                    danger
                                    size="small"
                                    onClick={() => this.handleDelete(record)}>删除</Button>
                        }
                    </Space>
                ),
            },
        ];
    }

    componentDidMount = () => {
        console.log(this.props.location.standardId)
        let receiveStandardId = ""
        if (this.props.location.standardId) {//判断当前有参数
            receiveStandardId = this.props.location.standardId;
            sessionStorage.setItem('standardId', receiveStandardId);// 存入到sessionStorage中
        } else {
            receiveStandardId = sessionStorage.getItem('standardId');// 当state没有参数时，取sessionStorage中的参数
        }
        this.setState({
            receiveStandardId: receiveStandardId
        }, () => this.getStandardMetaList())
        this.props.dispatch({
            type: "global/getByType",
            payload: {
                type: "INPUTTYPE"
            }
        }).then(res => {
            if (res) {
                this.setState({
                    typeList: res.data
                })
            }
        })
    }
    //编辑表格保存
    handleSave = (row) => {
        console.log(row, this.state.receiveStandardId)

        this.props.dispatch({
            type: "global/saveBasicFieldInfo",
            payload: {
                id: row.id,
                stId: this.state.receiveStandardId,
                limits: row.limits,
                name: row.name,
                sort: row.sort,
                type: row.type,
            }
        }).then(res => {
            console.log(res)
            if (res) {
                if (res.code == "1") {
                    message.success("更新成功！")
                    this.getStandardMetaList()
                } else {
                    message.error("更新失败")
                }
            } else {
                message.warning("保存前请先填写完整!")
            }
        })

    };
    //查询列表
    getStandardMetaList = () => {
        this.props.dispatch({
            type: "global/getBasicFieldInfoList",
            payload: {
                id: this.state.receiveStandardId
            }
        }).then(res => {
            if (res) {
                console.log(res)
                res.data.map((item1) => {
                    item1.key = item1.id
                    // this.state.typeList.map(item2=>{
                    //     if(item2.dicCode=item1.type){
                    //         item1.typeName=item2.dicName
                    //     }
                    // })
                })
                this.setState({
                    data: res.data
                })
            }
        })
    }
    //列表删除
    handleDelete = (record) => {
        console.log(record)
        this.props.dispatch({
            type: "global/deleteBasicFieldInfo",
            payload: {
                id: record.id
            }
        }).then(res => {
            console.log(res)
            if (res) {
                message.success("删除成功！")
                this.getStandardMetaList()
            }
        })
    }

    //列表新增一行
    createEvent = () => {
        let { data, } = this.state;
        const newData = {
            key: new Date(),
            name: <Input placeholder="请填写元数据名称" />,
            typeName: <Input placeholder="请选择元数据类型" />,
            limits: <Input placeholder="请填写元数据限制" />,
            sort: <Input placeholder="请填写元数据排序" />,
        };
        this.setState({
            data: [...data, newData],
        });
    }
    //新增，编辑提交
    handleSubmit = (values) => {
        console.log(values)
        console.log(this.state.beginmoreFormData)
        this.setState({
            isModalVisible: false
        })
        if (this.state.addFlag) {
            this.props.dispatch({
                type: "global/saveBasicFieldOptionInfo",
                payload: {
                    bdId: this.state.moreForm.bdId.toString(),
                    id: "",
                    name: values.names.slice(-1).toString(),
                    value: "",
                    sort: 1
                }
            }).then(res => {
                console.log(res)
                message.success("选项新增成功！")
            })
        } else {
            this.deleteSelectNodes()
        }
    }
    handleCancel = () => {
        this.setState({
            isModalVisible: false,
        })
    }
    //更多
    getMore = (record, flag) => {
        console.log(record, flag)
        if (flag === 1) {
            this.setState({
                addFlag: true
            })
        } else {
            this.setState({
                addFlag: false
            })
        }
        this.props.dispatch({
            type: "global/getBasicFieldOptionInfoById",
            payload: {
                id: record.id
            }
        }).then(res => {
            console.log(res)
            if (res) {
                let moreformData = []
                res.data.map((item, index) => {
                    moreformData[index] = item.name
                })
                console.log(moreformData)
                this.setState({
                    beginmoreFormData: res.data,
                    seValuelength: moreformData.length,
                    initvalue: moreformData,
                    isModalVisible: true,
                    modalTitle: `${record.typeName}选项`,
                    moreForm: {
                        bdId: record.id,
                    },
                })
            }
        })
    }

    //元数据选择项删除
    deleteSelectNodes = () => {
        this.props.dispatch({
            type: "global/deleteBasicFieldOptionInfo",
            payload: {
                id: this.state.deleteId
            }
        }).then(res => {
            if (res) {
                message.success("选项删除成功！")
                this.setState({
                    isModalVisible: false
                })
                this.getStandardMetaList()
            }
        })

    }
    handleonFieldsChange = (changedFields, allFields) => {
        console.log(changedFields, allFields)
        // console.log(this.state.beginmoreFormData)
        let id = ""
        this.state.beginmoreFormData.map((item, index) => {
            let INDEX = changedFields[0].value.indexOf(item.name)
            console.log(INDEX)
            if (INDEX == -1) {
                console.log(item.id, item.name)
                console.log(this.state.initvalue)
                this.setState({
                    deleteId: item.id
                })
            }
        })
        // console.log(id)
    }



    /////render函数
    render() {
        let { isModalVisible, initvalue, data, modalTitle, } = this.state;

        const components = {
            body: {
                row: EditableRow,
                cell: EditableCell,
            },
        };
        const columns = this.columns.map((col) => {
            if (!col.editable) {
                return col;
            }

            return {
                ...col,
                onCell: (record) => ({
                    record,
                    editable: col.editable,
                    dataIndex: col.dataIndex,
                    title: col.title,
                    handleSave: this.handleSave,
                    typeList: this.state.typeList,
                }),
            };
        });
        //更多动态增加内容
        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 4 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 20 },
            },
        };
        const formItemLayoutWithOutLabel = {
            wrapperCol: {
                xs: { span: 24, offset: 0 },
                sm: { span: 20, offset: 4 },
            },
        };

        return (
            <div>
                <div className={styles.pagetop}>
                    <span className={styles.pageheader}>
                        <Breadcrumb>
                            <Breadcrumb.Item><AppstoreTwoTone />标准与规范</Breadcrumb.Item>
                            <Breadcrumb.Item>
                                <a href="/assetstandard/standardList">标准列表</a>
                            </Breadcrumb.Item>
                            <Breadcrumb.Item>
                                <a href="/assetstandard/StandardMetaData">标准元数据列表</a>
                            </Breadcrumb.Item>
                        </Breadcrumb>
                    </span>
                </div>
                <div style={{ background: "white" }}>
                    <div style={{ padding: "10px 0" }}>
                        <Button type="primary"
                            icon={<PlusOutlined />}
                            style={{ marginLeft: "20px" }}
                            onClick={this.createEvent}>新增</Button>

                    </div>
                    <Table
                        components={components}
                        rowClassName={() => 'editable-row'}
                        columns={columns}
                        dataSource={data}
                        pagination={false}
                    />
                </div>
                {/* <div className={ styles.pagination }>
                    <Pagination
                        total={ data.length }
                        showSizeChanger
                        showQuickJumper
                        showTotal={ total => `共 ${total} 条` }
                        onChange={ this.pageChange }
                        onShowSizeChange={ this.pageSizeChange }
                    />
                </div> */}
                {
                    isModalVisible ?
                        <Modal
                            title={modalTitle}
                            centered
                            closable={false}
                            okText="保存"
                            width={400}
                            visible={isModalVisible}
                            footer={false}
                            closable
                            onCancel={this.handleCancel}
                        >
                            <Form name="dynamic_form_item" {...formItemLayoutWithOutLabel} onFinish={this.handleSubmit} onFieldsChange={this.handleonFieldsChange}>
                                <Form.List name="names" initialValue={initvalue}>
                                    {(fields, { add, remove }, { errors }) => (
                                        <>
                                            {fields.map((field, index) => (
                                                <Form.Item
                                                    {...(index === 0 ? formItemLayout : formItemLayoutWithOutLabel)}
                                                    label={index === 0 ? '选项' : ''}
                                                    required={false}
                                                    key={field.key}
                                                >
                                                    <Form.Item
                                                        {...field}
                                                        validateTrigger={['onChange', 'onBlur']}
                                                        rules={[
                                                            {
                                                                required: true,
                                                                whitespace: true,
                                                                message: "Please input it or delete this field.",
                                                            },
                                                        ]}
                                                        noStyle
                                                    >
                                                        <Input placeholder="选择项名称" style={{ width: '60%' }} disabled={!this.state.addFlag} />
                                                    </Form.Item>
                                                    {index === fields.length - 1 && fields.length === this.state.seValuelength && !this.state.addFlag ? (
                                                        <MinusCircleOutlined
                                                            className="dynamic-delete-button"
                                                            onClick={() => remove(field.name)}
                                                        />
                                                    ) : null}
                                                </Form.Item>
                                            ))}
                                            <Form.Item>
                                                {
                                                    fields.length < this.state.seValuelength + 1 && this.state.addFlag ?
                                                        <Button
                                                            type="dashed"
                                                            onClick={() => add()}
                                                            style={{ width: '60%' }}
                                                            icon={<PlusOutlined />}
                                                        >
                                                            增加
                                                </Button> : null
                                                }
                                                <Form.ErrorList errors={errors} />
                                            </Form.Item>
                                        </>
                                    )}
                                </Form.List>
                                <Form.Item>
                                    <Button onClick={this.handleCancel} style={{ align: "center", margin: "0 16px" }}>
                                        取消
                                    </Button>
                                    <Button type="primary" htmlType="submit">
                                        保存
                                    </Button>
                                </Form.Item>
                            </Form>
                        </Modal> : null
                }

            </div>
        );
    }
}

export default StandardMetaDataForm;